/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: UpdateResponseWrapper.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.baselib.update;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;

import java.lang.ref.WeakReference;

import io.bhex.baselib.network.response.ResponseListener;


public class UpdateResponseWrapper<T extends UpdateResponseIntf> implements ResponseListener<T> {
    private WeakReference<Context> context;
    private ResponseListener<T> base;
    private UpdateReturnListener updateListener;

    public UpdateResponseWrapper(Context context, ResponseListener<T> listener, UpdateReturnListener updateListener) {
        this.context = new WeakReference<>(context);
        base = listener;
        this.updateListener = updateListener;
    }

    @Override
    public void onSuccess(T response) {
        base.onSuccess(response);

        if (response == null)
            return;

        //没有更新
        if (!response.isHasUpdate()) {
            if (updateListener != null) {
                updateListener.onNoUpdate(response);
            }
            return;
        }


        if (context == null || context.get() == null)
            return;

        if (isVersionIgnored(response) && !UpdateConfig.isUpdateForce())
            return;

        showUpdateDialog(response);

        if (updateListener != null)
            updateListener.onHasUpdate(response);
    }

    private void showUpdateDialog(T response) {
        Intent intent = new Intent();

        intent.setClass(context.get(), UpdateDialogActivity.class);
        intent.putExtra(UpdateDialogActivity.UPDATE_DATA, response);
        context.get().startActivity(intent);
    }

    /**
     * 更新是否被忽略了
     *
     * @param response
     * @return
     */
    private boolean isVersionIgnored(T response) {
        return UpdateConfig.getIgnoredMd5(context.get()).equals(response.getFileMd5());
    }

    @Override
    public void onBefore() {
        base.onBefore();
    }

    @Override
    public void onFinish() {
        base.onFinish();
    }

    @Override
    public void onError(Throwable error) {
        base.onError(error);

        if (updateListener != null) {
            updateListener.onError();
        }
    }

    @Override
    public void onAfter() {
        base.onAfter();
    }

    @Override
    public T parserResponse(Handler uiHandler, String response, Class<T> clazz) {
        return base.parserResponse(uiHandler, response, clazz);
    }
}
